'''
Created on 5 mai 2010

@author: philip
'''
import logging 
from django.http import HttpResponse, Http404
from place_service import PlaceService, POIUpdateScheduleRequest, POIUpdateContext
from django.shortcuts import render_to_response
from osm_service import OSMMapDataRequest,OSMService
from places.models import Place
from django.utils import simplejson
import helpers
from communities.community_service import CommunityService

def index(request, communityId):
    community = CommunityService().getCommunity(communityId)
    if community is None: raise Http404
    categories = helpers.getCategories()
    return render_to_response("places/places.html",{"community":community, "categories":categories})

def find(request):
    community = request.REQUEST["community"]
    category = request.REQUEST["category"]
    places = Place.objects.filter(community_id=community,categories=category)
    if request.is_ajax():
        return HttpResponse(simplejson.dumps({"community":community,"category":category,"places":places},
                                            default=Place.toJSON),mimetype="application/json")
    else:
        return render_to_response("places/places_find.html",{"places":places})

def parse(request):
    r = request.REQUEST
    validInput = r.has_key("lat1") and r.has_key("lon1") and r.has_key("lat2") and r.has_key("lon2")
    
    if not validInput: return HttpResponse("invalid input")
    
    mapService = OSMService()
    data = mapService.getMapData(OSMMapDataRequest(r["lat1"], r["lon1"], r["lat2"], r["lon2"])) 
    
    os = mapService.parseMapData(data)
    
    return render_to_response("wires/poi_update_parse.html",
                              {"lat1":r["lat1"], "lon1":r["lon1"], "lat2":r["lat2"], "lon2":r["lon2"],
                               "results":os
                               })

def updatePOIsTask(request):
    # INPUT
    # * community -- community id
    # * clat -- central latitude
    # * clon -- central longitude
    # * r -- radius
    # ------------------------------------
    # --SECONDARY params
    # * plat -- previous latitude
    # * plon -- previous longitude
    # * minlat -- minimum latitude
    # * minlon -- minimum longitude
    # * maxlat -- maximum latitude
    # * maxlon -- maximum longitude
    # if one or more of the secondary params is not provided, new update for the given are is scheduled
    
    r = request.REQUEST
    
    
    #validate and figure out what to do based on the input
    isRequestValid = r.has_key("clat") and r.has_key("clon") and r.has_key("r") and r.has_key("community")
    
    if not isRequestValid: 
        logging.error("POI update error (invalid input): %s" % request.REQUEST)
        return HttpResponse("invalid request")
    
    isSchedule = len(r.items()) == 4
    
    if isSchedule:
        logging.debug("scheduling POI update: %s" % request.REQUEST)
        d = PlaceService().schedulePOIUpdate(POIUpdateScheduleRequest(r["community"],r["clat"],r["clon"],r["r"]))
        return render_to_response("wires/poi_update_summary.html",d)
    else:
        context = POIUpdateContext(r)
        if not context.isValidRequest():
            logging.error("invalid poi update request: %s" % r)
            return HttpResponse("invalid poi update")
        logging.debug("running POI update: %s" % request.REQUEST)
        data = PlaceService().runPOIUpdate(context.parseContext())
        return render_to_response("wires/poi_update_parse.html", {"results":data})